package com.xm2.demo.system.customer.service;

import com.xm2.demo.model.User;
import com.xm2.demo.system.customer.dao.CustomerRepository;
import com.xm2.demo.utils.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author
 * @Date 2018/12/14 11:19
 * @Description
 */
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    // 分页
    @Override
    public Pagination findByPositionId(Pagination pagination) {
        pagination.setTotalRows(customerRepository.findByPositionId(0).size());
        Pageable pageable = new PageRequest(pagination.getCurrentPage(), pagination.getSize(), Sort.Direction.ASC, "id");
        pagination.setList(customerRepository.findByPositionId(0,pageable));
        return pagination;
    }
    // 修改
    @Override
    @Transactional
    public void updateUser(User user) {
        customerRepository.updateUserPhone(user.getUsername(),user.getPhone());
    }
    //添加
    @Override
    public void addUser(User user) throws Exception {
        Integer size = findByUsernameAndPositionId(user.getUsername(),0).size();
        if(size == 0 ){
        customerRepository.save(user);
        }else{
            throw new Exception("用户以存在");
        }
    }

    // 根据用户名查询
    @Override
    public List<User> findByUsernameAndPositionId(String username, Integer i) {
        return customerRepository.findByUsernameAndPositionId(username,0);
    }
    // 删除用户
    @Override
    @Transactional
    public void deleteUsername(Integer[] ids) throws Exception {
        for(int i = 0 ; i< ids.length; i++){
            User user = customerRepository.findById(ids[i]);
                if (user.getBalance()!=0){
                    throw new Exception("有用户余额不为0");
                }
            customerRepository.delete(ids[i]);
        }
    }


}
